package com.lsq.baseadmin.modules.manage.utils;

import com.lsq.baseadmin.modules.maintenance.entity.Menu;
import com.lsq.baseadmin.modules.maintenance.vo.MenuVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author pc12138
 * @since 2020/10/25 22:58
 */
public class MenuTreeUtil {

    public static List<MenuVo> buildTree(List<Menu> menus) {
        List<MenuVo> menuVoList = new ArrayList<>();
        for (Menu menu : menus) {
            if (null != menu.getParentId() && menu.getParentId() != 0) {
                continue;
            }

            MenuVo vo = new MenuVo();
            BeanUtils.copyProperties(menu, vo);
            menuVoList.add(vo);

            List<MenuVo> chVoList = new ArrayList<>();
            for (Menu ch : menus) {
                if (null == ch.getParentId() || !ch.getParentId().equals(menu.getId())) {
                    continue;
                }
                MenuVo chVo = new MenuVo();
                BeanUtils.copyProperties(ch, chVo);
                chVoList.add(chVo);
            }
            vo.setChildren(chVoList);


        }
        return menuVoList;
    }

    /**
     * 使用递归方法建树结构:查询时用，因输入的条件没有 最顶级的菜单 会生成不了数据
     * @param menus List
     * @return List
     */
    public static List<MenuVo> queryBuildTreeByRecursive(List<Menu> menus) {
        List<MenuVo> trees = new ArrayList<>();
        if(menus == null || menus.size() < 1){
            return trees;
        }

        for (Menu menu : menus) {
            trees.add(findChildren(menu,menus));
        }
        return trees;
    }
    /**
     * 使用递归方法建树结构
     * @param menus List
     * @return List
     */
    public static List<MenuVo> buildTreeByRecursive(List<Menu> menus) {
        List<MenuVo> trees = new ArrayList<>();
        if(menus == null || menus.size() < 1){
            return trees;
        }

        for (Menu menu : menus) {
            if (0 == menu.getParentId()) {
                trees.add(findChildren(menu,menus));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     */
    private static MenuVo findChildren(Menu menu, List<Menu> menus) {
        MenuVo menuVo = new MenuVo();
        BeanUtils.copyProperties(menu, menuVo);
        if(menus == null || menus.size() < 1){
            return menuVo;
        }

        for (Menu ch : menus) {
            if(menuVo.getId().equals(ch.getParentId())) {
                if (menuVo.getChildren() == null) {
                    menuVo.setChildren(new ArrayList<>());
                }
                menuVo.getChildren().add(findChildren(ch, menus));
            }
        }
        return menuVo;
    }

}
